import React from "react";
import { Form, Input, Button, Radio, Alert, Row, Col, Table, Tooltip, Switch, Modal } from "antd";
import UserSelectModal from "components/userSelectModal/UserSelectModal";
// import TodoListSelect from "components/todoListSelect"
import FlowConfigSelect from "components/flowConfigSelect"
import Zcon from "@cbd/icon";
import setTimeout from "core-js/fn/set-timeout";
import { connect } from "dva";
import { openNotificationWithIcon } from "../../../../utils/comm";

const { confirm } = Modal;
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16},
}



@Form.create()
@connect(({ Entrust }) => ({
  entrustStore: Entrust,
}))
class StepTwo extends React.Component {
  checkedNodes = [];

  constructor(props) {
    super(props);
    this.state = {
      overlayVisible: false,
      // checkedKeys:[],
      selectUserType: '',
      customedEntrust: false,
      customedEntrustDataList: [
        // {
        //   entrustExist: 0,
        //   entrustReason: '',
        //   flowName: '',
        //   modelKey: '',
        //   status: 0,
        //   trustee: '',
        //   trusteeCode: '',
        //   trusteeDepartmentCode: '',
        // },
      ],
      customedEntrustDataListCheckedKeys: [],
      customedEntrustDataListCheckedRows: [],
      todoListSelectVisible: false,
      editCustomedEntrustDataListIndex: null,
    }
    this.columns = [
      {
        title: "流程名称",
        align: 'center',
        dataIndex: "flowName",
        // key: "flowName",
        width: '60px',
        render: (text, record, index) => {
          return (
            <Input
              placeholder="请点击图标选择"
              disabled
              style={{ width: '150px' }}
              value={text}
              suffix={
                <Zcon
                  onClick={() => this.setState({ todoListSelectVisible: true, editCustomedEntrustDataListIndex: index})}
                  style={{ color: "rgba(0,0,0,0.25)", cursor: "pointer" }}
                  title="点击进行选择"
                  type="search"
                />
                }
            />
          );
        },
      },
      {
        title: "受托人",
        align: 'center',
        dataIndex: "trustee",
        // key: "modelKey",
        width: '60px',
        render: (text, record, index) => {
          return (
            <Input
              placeholder="请点击图标选择"
              disabled
              style={{ width: '150px' }}
              value={text}
              suffix={
                <Zcon
                  onClick={() => this.setState({ overlayVisible: true, selectUserType: 'tableItem', editCustomedEntrustDataListIndex: index})}
                  style={{ color: "rgba(0,0,0,0.25)", cursor: "pointer" }}
                  title="点击进行选择"
                  type="search"
                />
                }
            />
          );
        },
      },
      {
        title: "受托人部门",
        align: 'center',
        dataIndex: "trusteeDepartment",
        // key: "modelKey",
        width: '60px',
        render: (v) => {
          return (
            <span
              title={v}
            >
              {v}
            </span>
          );
        },
      },
      {
        title: "移交原因",
        align: 'center',
        dataIndex: "entrustReason",
        // key: "modelKey",
        width: '60px',
        render: (text, record) => {
          return (
            <Input
              onChange={(e) => {
                record.entrustReason = e.target.value;
            }}
              defaultValue={text}
            />
          );
        },
      },
      {
        title: "委托已有代办事宜",
        align: 'center',
        dataIndex: "entrustExist",
        // key: "modelKey",
        width: '60px',
        render: (text, record) => {
          return (
            <Switch
              defaultChecked={text!==0}
              onChange={(val) => {
                if(val) {
                  record.entrustExist = 1;
                } else {
                  record.entrustExist = 0;
                }
          }}
              checkedChildren="开"
              unCheckedChildren="关"
            />
          );
        },
      },
      {
        title: "操作",
        align: 'center',
        dataIndex: "modelKey",
        key: "modelKey",
        width: '60px',
        render: (v, record, index) => {
          return (
            <span
              style={{paddingLeft:'5px',color:'#1890FF', cursor: 'pointer'}}
              onClick={() => {
                // eslint-disable-next-line prefer-destructuring
                const handleCustomedEntrustTableItemDelete = this.handleCustomedEntrustTableItemDelete;
                confirm({
                  title: '确定删除这一项吗?',
                  okText:'确定',
                  cancelText: '取消',
                  onOk() {
                    handleCustomedEntrustTableItemDelete(index, record);
                  },
                  onCancel() {},
                });
            }}
            >
              删除
            </span>
          );
        },
      },
    ];
    this.rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({customedEntrustDataListCheckedRows:selectedRows, customedEntrustDataListCheckedKeys: selectedRowKeys})
      },
    };
  }

  componentDidMount() {
    const {
      entrustDetailData,
    } = this.props;
    let flag = false;
    if(entrustDetailData.flowEntrustDetailVoList) {
      entrustDetailData.flowEntrustDetailVoList.forEach((item) => {
        if(item.status === 1) {
          flag = true;
        }
      })
      // this.setState((state)=> {
      //   return {
      //     customedEntrust: flag,
      //   }
      // },()=> {
      //   console.log(this.state)
      // })
      this.setState({customedEntrust: flag})
      this.setState({customedEntrustDataList: entrustDetailData.flowEntrustDetailVoList})
    }
  }

  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
  };

  handleCancel = () => {
    const { handleEntrustDetailVisible } = this.props;
    handleEntrustDetailVisible(false)
  };

  checkCustomedEntrustDataList = (list) => {
    const result = {
      err: false,
      msg: '',
    }
    for (let i = 0; i < list.length; i +=1) {
      if (list[i].flowName === '') {
        result.err = true
        result.msg = '请选择自定义委托中的流程名称'
        break;
      }
      if (list[i].trustee === '') {
        result.err = true
        result.msg = '请选择自定义委托中的委托人'
        break;
      }
      if (list[i].entrustReason === '') {
        result.err = true
        result.msg = '请填写自定义委托中的移交原因'
        break;
      }
      if (list[i].entrustReason.length > 150) {
        result.err = true
        result.msg = '自定义委托中的移交原因字数最多150字，请检查！'
        break;
      }
    }
    return result;
  }

  handleNextStep = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { form, nextStep } = this.props;
    const { customedEntrust, customedEntrustDataList } = this.state;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      values.customedEntrust = customedEntrust;
      const checkResult = this.checkCustomedEntrustDataList(customedEntrustDataList);
      if(checkResult.err) {
        openNotificationWithIcon("warning", "", checkResult.msg);
        return;
      }
      customedEntrustDataList.forEach((item) => {
        item.status = customedEntrust ? 1 : 0;
      })
      values.flowEntrustDetailVoList = customedEntrustDataList;
      confirm({
        title: '确定提交吗?',
        okText:'确定',
        cancelText: '取消',
        onOk: () => {
          nextStep(values)
        },
      });
    });
  }

  handleLastStep = () => {
    const { form, lastStep } = this.props;
    const { customedEntrust, customedEntrustDataList } = this.state;
    form.validateFields((err, values) => {
      values.customedEntrust = customedEntrust;
      values.flowEntrustDetailVoList = customedEntrustDataList;
      lastStep(values)
    });
  }

  checkTree = (checkedKeys, checkedNodes) => {
    const { form } = this.props;
    const { selectUserType, editCustomedEntrustDataListIndex, customedEntrustDataList } = this.state;
    // const value = checkedNodes[0].props.title
    const value = checkedNodes[0]
    if(value && selectUserType === 'trustee') {
      form.setFieldsValue({ trustee: value.props.title });
      form.setFieldsValue({ trusteeCode: value.key });
      form.setFieldsValue({ trusteeDepartment: value.props.dataRef.extentAttributes.ORG_NAME });
      form.setFieldsValue({ trusteeDepartmentCode: value.props.dataRef.extentAttributes.ORG_CODE });
    } else if (value && selectUserType === 'tableItem') {
      customedEntrustDataList[editCustomedEntrustDataListIndex].trustee = value.props.title;
      customedEntrustDataList[editCustomedEntrustDataListIndex].trusteeCode = value.key;
      customedEntrustDataList[editCustomedEntrustDataListIndex].trusteeDepartment = value.props.dataRef.extentAttributes.ORG_NAME;
      customedEntrustDataList[editCustomedEntrustDataListIndex].trusteeDepartmentCode = value.props.dataRef.extentAttributes.ORG_CODE;
      this.setState({
        customedEntrustDataList,
      })
    }
    this.checkedNodes = checkedNodes;
    // this.setState({ checkedKeys });
  };

  handleCustomedEntrust = (checked) => {
    const { form } = this.props;
    form.setFieldsValue({ customedEntrust: checked });
    this.setState({customedEntrust: checked})
    setTimeout(()=> {
      this.flowDiv.scrollTop = this.flowDiv.offsetHeight;
    },0)
  }

  handleCustomedEntrustAdd = () => {
    const { customedEntrustDataList } = this.state;
    this.setState({ customedEntrustDataList: [...customedEntrustDataList, {
      entrustExist: 0,
      entrustReason: '',
      flowName: '',
      modelKey: '',
      status: 0,
      trustee: '',
      trusteeDepartment: '',
      trusteeCode: '',
      trusteeDepartmentCode: '',
    }]})
  }

  handleCustomedEntrustDelete = ()=> {
    const { customedEntrustDataListCheckedKeys, customedEntrustDataListCheckedRows } = this.state;
    if (customedEntrustDataListCheckedKeys.length === 0) {
      openNotificationWithIcon("warning", "", '请先选择要删除的数据');
    } else {
      const handle = this.handleDelete
      confirm({
        title: '确定删除选中的项吗?',
        okText:'确定',
        cancelText: '取消',
        onOk() {
          handle(customedEntrustDataListCheckedKeys, customedEntrustDataListCheckedRows)
        },
        onCancel() {},
      });
      // customedEntrustDataListCheckedRows.forEach((item)=> {
      //   customedEntrustDataList.splice(item, 1)
      // })
      // this.setState({customedEntrustDataList})
    }
  }

  handleCustomedEntrustTableItemDelete = (index, row) => {
    const keyList = [index];
    const rowList = [row];
    this.handleDelete(keyList, rowList)
    // const {  customedEntrustDataList } = this.state;
    // customedEntrustDataList.splice(index, 1)
    // this.setState({customedEntrustDataList})
  }

  handleDelete = (keyList, rowList) => {
    const ids = [];
    rowList.forEach((item) => {
      if(item.id) {
        ids.push(item.id)
      }
    })
    const { dispatch } = this.props;
    const { customedEntrustDataList } = this.state;

    if(ids.length === 0) {
      for(let i = keyList.length - 1; i >= 0; i-=1) {
        customedEntrustDataList.splice(keyList[i], 1)
      }
      this.setState({customedEntrustDataList, customedEntrustDataListCheckedKeys: [], customedEntrustDataListCheckedRows: []});
    } else {
      dispatch({ type: "Entrust/deleteDetailDataList", payload: { ids } }).then((res) => {
        if (res.errCode === 0) {
          openNotificationWithIcon("success", "", "删除成功");
          for(let i = keyList.length - 1; i >= 0; i-=1) {
            customedEntrustDataList.splice(keyList[i], 1)
          }
          this.setState({customedEntrustDataList, customedEntrustDataListCheckedKeys: [], customedEntrustDataListCheckedRows: []});
        } else {
          openNotificationWithIcon("error", "", res.errMsg || "删除失败");
        }
      })
    }
  }


  handleTodoListSelect = (item) => {
    const { todoListSelectVisible, editCustomedEntrustDataListIndex, customedEntrustDataList } = this.state
    if(!item) {
      this.setState({todoListSelectVisible: !todoListSelectVisible});
      return;
    }
    let flag = false;
    customedEntrustDataList.forEach((it) => {
      if(it.modelKey === item.modelKey) {
        flag = true
      }
    })
    if(flag) {
      openNotificationWithIcon("warning", "", '流程模型重复，请重新选择！');
   } else {
      if(item) {
        customedEntrustDataList[editCustomedEntrustDataListIndex].flowName = item.modelName;
        customedEntrustDataList[editCustomedEntrustDataListIndex].modelKey = item.modelKey;
        this.setState({
          customedEntrustDataList,
        })
      }
      this.setState({todoListSelectVisible: !todoListSelectVisible})
    }
  }

  renderUserSelect() {
    const { overlayVisible } = this.state;
    const { dispatch, userTitle } = this.props;
    return (
      <UserSelectModal
        title={userTitle}
        checkedKeys={[]}
        checkedNodes={[]}
        dispatch={dispatch}
        onCancel={() => this.setState({ overlayVisible: false })}
        onOk={this.checkTree}
        visible={overlayVisible}
        selectNumLimit={1}
      />
    );
  }

  render() {
    const {
      entrustDetailData,
      form,
    } = this.props;
    const { getFieldDecorator } = form;
    const { customedEntrust, customedEntrustDataList, todoListSelectVisible } = this.state;
    return (
      <div ref={(ref)=>{this.flowDiv = ref}} style={{width:'100%',overflow:'auto'}}>
        <div style={{width:'99%'}}>
          <Alert
            message="确认委托信息后，流程将自动流向受托人"
            type="info"
            closable
            showIcon
          />
        </div>
        <div style={{paddingTop:'10px',width:'99%'}}>
          <Form>
            <Row>
              <Col span={12}>
                <Form.Item label="委托人" {...formItemLayout}>
                  {getFieldDecorator("client", {
                initialValue: entrustDetailData.client || sessionStorage.getItem("USER_NAME"),
                rules: [
                  // { required: true, message: "请输入委托名称" },
                  // { max: 20, message: "流程名称长度不能超过20" },
                ],
              })(
                // <Search
                //   placeholder="请选择委托人"
                //   onSearch={() => this.setState({ overlayVisible: true, selectUserType: 'entrustName'})}
                //   disabled
                //   enterButton
                // />
                <Input
                  placeholder="默认为当前登录用户"
                  className="input__search"
                  disabled
                  style={{ width: '246px' }}
                //   suffix={
                //     <Zcon
                //       onClick={() => this.setState({ overlayVisible: true, selectUserType: 'client'})}
                //       style={{ color: "rgba(0,0,0,0.25)", cursor: "pointer" }}
                //       title="点击进行选择"
                //       type="search"
                //     />
                // }
                />
                )}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="委托人部门" {...formItemLayout}>
                  {getFieldDecorator("clientDepartment", {
                initialValue: entrustDetailData.clientDepartment || sessionStorage.getItem("USER_ORGNAME"),
                rules: [
                  // { required: true, message: "请输入委托人部门" },
                  // { max: 20, message: "编码长度不能超过20" },
                ],
              })(<Input disabled placeholder="默认为当前登录用户部门" />)}
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="默认受托人" {...formItemLayout}>
                  {getFieldDecorator("trustee", {
                initialValue: entrustDetailData.trustee,
                rules: [
                  { required: true, message: "请选择受托人" },
                  // { max: 20, message: "流程名称长度不能超过20" },
                ],
              })(
                <Input
                  placeholder="请点击图标选择受托人"
                  className="input__search"
                  disabled
                  style={{ width: '246px' }}
                  suffix={
                    <Zcon
                      onClick={() => this.setState({ overlayVisible: true, selectUserType: 'trustee'})}
                      style={{ color: "rgba(0,0,0,0.25)", cursor: "pointer" }}
                      title="点击进行选择"
                      type="search"
                    />
                }
                />
              )}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="默认受托人部门" {...formItemLayout}>
                  {getFieldDecorator("trusteeDepartment", {
                initialValue: entrustDetailData.trusteeDepartment,
                rules: [
                  { required: true, message: "选择受托人后自动填充" },
                  // { max: 20, message: "编码长度不能超过20" },
                ],
              })(<Input disabled placeholder="选择受托人后自动填充" />)}
                </Form.Item>
              </Col>
            </Row>
            <Row style={{display:'none'}}>
              <Col span={12}>
                <Form.Item label="" {...formItemLayout}>
                  {getFieldDecorator("trusteeCode", {
                rules: [
                  // { required: true, message: "" },
                  // { max: 20, message: "流程名称长度不能超过20" },
                ],
              })(
                <Input />
              )}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="" {...formItemLayout}>
                  {getFieldDecorator("trusteeDepartmentCode", {
                rules: [
                  // { required: true, message: "" },
                  // { max: 20, message: "编码长度不能超过20" },
                ],
              })(<Input />)}
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="委托已有代办事宜" {...formItemLayout}>
                  {getFieldDecorator("entrustExist", {
                initialValue: entrustDetailData.entrustExist,
                rules: [
                  { required: true, message: "请选择" },
                  // { max: 20, message: "编码长度不能超过20" },
                ],
              })(
                <Radio.Group>
                  <Radio value={1}>是</Radio>
                  <Radio value={0}>否</Radio>
                </Radio.Group>
              )}
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="移交原因" {...formItemLayout}>
                  {getFieldDecorator("entrustReason", {
                initialValue: entrustDetailData.entrustReason,
                rules: [
                  { required: true, message: "请输入移交原因" },
                  { max: 200, message: "编码长度不能超过200" },
                ],
              })(<Input maxLength={20} placeholder="请输入移交原因" />)}
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item label="自定义委托" {...formItemLayout}>
                  {getFieldDecorator("customedEntrust", {
                initialValue: customedEntrust,
                valuePropName: 'checked',
                rules: [
                  // { required: true, message: "请输入委托编码" },
                  // { max: 20, message: "编码长度不能超过20" },
                ],
              })(
                // <div>
                //   <Tooltip title="除自定义委托涉及到的流程，其他流程默认使用默认委托处理">
                //     <Zcon type="question-circle-o" />
                //   </Tooltip>
                //   <span style={{paddingLeft:'10px'}}>
                <Switch onChange={this.handleCustomedEntrust} checkedChildren="开" unCheckedChildren="关" />
                //   </span>
                // </div>
              )}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="" {...formItemLayout}>
                  <div>
                    <Tooltip title="除自定义委托涉及到的流程，其他流程默认使用默认委托处理">
                      <Zcon type="question-circle-o" />
                    </Tooltip>
                    <span style={{paddingLeft:'10px'}} />
                  </div>
                </Form.Item>
              </Col>
            </Row>
          </Form>
          {
            customedEntrust &&
            (
              <div>
                <div style={{display:'flex', justifyContent:'end', paddingBottom:'10px'}}>
                  <Button style={{ marginLeft: '5px'}} className='list__btn' size="small" onClick={this.handleCustomedEntrustAdd}>
                    新增
                  </Button>
                  <Button className='list__btn' style={{marginLeft: '10px'}} type="primary" size="small" onClick={this.handleCustomedEntrustDelete}>
                    删除
                  </Button>
                </div>
                <Table
                  dataSource={customedEntrustDataList}
            // loading={listLoading}
                  columns={this.columns}
            // scroll={{x: 1200}}
                  // rowKey="modelId"
                  bordered
                  rowSelection={this.rowSelection}
                />
              </div>
            )
          }
          <div style={{display:'flex', justifyContent:'center', paddingTop:'10px'}}>
            <Button style={{ marginLeft: '5px'}} className='list__btn' type="primary" onClick={this.handleNextStep}>
              提交
            </Button>
            <Button className='list__btn' style={{marginLeft: '20px'}} onClick={this.handleLastStep}>
              修改默认委托信息
            </Button>
          </div>
        </div>
        {/* <TodoListSelect
          visible={todoListSelectVisible}
          handleClose={this.handleTodoListSelect}
        /> */}
        <FlowConfigSelect
          visible={todoListSelectVisible}
          handleClose={this.handleTodoListSelect}
        />
        {this.renderUserSelect()}
      </div>
    )
  }
}

export default StepTwo;
